const fs = require('fs-extra');
const path = require('path');

class TemplateReader {
  constructor(templatePath) {
    this.templatePath = templatePath;
  }

  async getTemplates() {
    try {
      const templates = {};
      const pagesPath = path.resolve(this.templatePath);
      console.log('Reading templates from:', pagesPath);
      
      // 确保目录存在
      if (!await fs.pathExists(pagesPath)) {
        throw new Error(`Template directory not found: ${pagesPath}`);
      }

      const pages = await fs.readdir(pagesPath);
      
      for (const page of pages) {
        const pagePath = path.join(pagesPath, page);
        const stats = await fs.stat(pagePath);
        
        if (stats.isDirectory()) {
          const fileNamePath = path.join(pagePath, 'fileName');
          
          // 检查fileName文件是否存在
          if (await fs.pathExists(fileNamePath)) {
            const content = await fs.readFile(fileNamePath, 'utf8');
            console.log(`Found template for ${page}:`, content.substring(0, 100));
            
            templates[page] = {
              prompt: content,
              outputPath: path.join(page, 'index.ux')
            };
          } else {
            console.log(`No fileName found in ${pagePath}`);
          }
        }
      }
      
      return templates;
    } catch (error) {
      console.error('Error reading templates:', error);
      throw error;
    }
  }
}

module.exports = TemplateReader; 